package risk.control.project.framework.service;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import risk.control.project.config.constant.ServiceName;
import risk.control.project.framework.base.BaseEncryption;

import java.util.HashMap;

/**
 * 处理请求基础信息服务
 */
@Service
public class BaseHandleService extends BaseEncryption {

    private static final Logger logger = LoggerFactory.getLogger(BaseHandleService.class);

    /**
     * 获取请求的基本信息
     *
     * @param req HttpServletRequest
     * @return 1、sessionId
     * 2、requestBody
     * 3、serveName
     */
    public HashMap<String, String> getRequestInfo(HttpServletRequest req) {
        HashMap<String, String> resMap = new HashMap<>();
        try {
            String sessionId = req.getHeader("sessionId");
            String requestBody = req.getReader().readLine();
            //解析url
            String requestUrl = req.getRequestURL().toString();
            String[] arr = requestUrl.split("/");
            int index = arr.length - 1;//获取最后一个元素
            String serveName = arr[index];
            //封装返回信息
            resMap.put("sessionId", sessionId);
            resMap.put("requestBody", requestBody);
            resMap.put("serveName", serveName);
            return resMap;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密请求体
     *
     * @param requestBody requestBody
     * @return 真实请求体
     */
    public String decryptRequestBody(String requestBody) {
        if (requestBody == null || requestBody.isEmpty()) {
            return "";
        }
        return BaseDecrypt(requestBody);
    }

    /**
     * 校验服务名（api）的合法性
     *
     * @param serveName serveName请求链接的最后一个元素
     * @return resMap
     */
    public HashMap<String, String> verifierServiceName(String serveName) {
        HashMap<String, String> resMap = new HashMap<>();
        if (serveName == null || serveName.isEmpty()) {
            resMap.put("state", "001");
            resMap.put("msg", "serveName异常");
            return resMap;
        }
        //校验service是否有注册-校验合法性
        String s = ServiceName.Map.get(serveName);
        if (s == null || s.isEmpty()) {
            resMap.put("state", "002");
            resMap.put("msg", "serveName未注册");
            return resMap;
        }
        resMap.put("state", "000");
        resMap.put("msg", "serveName校验通过");
        return resMap;
    }
}
